package com.tohours.aia.constants;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.dom4j.Document;
import org.dom4j.io.SAXReader;

public class WebService {

	/**
	 * 
	 * @param userName 用户名
	 * @param password 密码
	 * @param type 奖励类型
	 * @param name 客户名称
	 * @param cellPhone 客户手机
	 * @param number 保单号码
	 * @return
	 * @throws Exception
	 */
	public static String reward(String userName, String password, String type, String name, String cellPhone, String number) throws Exception{
		StringBuffer xml = new StringBuffer();
		xml.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		xml.append("<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns1=\"usr_service\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">");
		xml.append("  <SOAP-ENV:Body>");
		xml.append("    <ns1:GetCode>");
		xml.append(String.format("      <param0 xsi:type=\"xsd:string\">%s</param0>", userName));
		xml.append(String.format("      <param1 xsi:type=\"xsd:string\">%s</param1>", password));
		xml.append(String.format("      <param2 xsi:type=\"xsd:string\">%s</param2>", type));
		xml.append(String.format("      <param3 xsi:type=\"xsd:string\">%s</param3>", name));
		xml.append(String.format("      <param4 xsi:type=\"xsd:string\">%s</param4>", cellPhone));
		xml.append(String.format("      <param5 xsi:type=\"xsd:string\">%s</param5>", number));
		xml.append("    </ns1:GetCode>");
		xml.append("  </SOAP-ENV:Body>");
		xml.append("</SOAP-ENV:Envelope>");

		URL url = new URL("http://www.tlcmarketing.cn/webservice/userServer.php");
		HttpURLConnection hc = (HttpURLConnection) url.openConnection();
		//hc.setRequestProperty("SOAPAction", "\"usr_service#GetCode\"");
		//hc.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
		hc.setDoOutput(true);
		OutputStream os = hc.getOutputStream();
		os.write(xml.toString().getBytes("UTF-8"));
		InputStream input = null;
		String rv = null;
		if (hc.getResponseCode() >= 400) {
			input = hc.getErrorStream();
			rv = TohoursUtils.inputStream2String(input);
			throw new Exception(rv);
		} else {
			input = hc.getInputStream();
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(input);
			rv = document.selectSingleNode("/SOAP-ENV:Envelope/SOAP-ENV:Body/ns1:GetCodeResponse/return").getText();
		}
		return rv;
	}
}
